using UnityEngine;

namespace Game.Networking.Server {
	public sealed class ServerGameController : ServerSideController<ServerGameController> {
		const int   InitialAsteroidCount = 40;
		const float AsteroidSpawnRadius  = 550;

		static Vector3 RedTeamPos = new Vector3(0, 0, -1500);
		static Vector3 BlueTeamPos = new Vector3(0, 0, 1500);

		public const string StateFileName = "game.info";
		GameControllerData _state = new GameControllerData();

		public ServerGameController(ServerGameManager owner) : base(owner) {
		}

		public override void Load() {
			base.Load();
			var loaded = ServerSaveLoadController.Instance.LoadSaveFile<GameControllerData>(StateFileName);
			if ( loaded != null ) {
				_state = loaded;
			}
		}

		public override void PostLoad() {
			base.PostLoad();
			if ( _state.AsteroidCount < InitialAsteroidCount ) {
				var toSpawn = InitialAsteroidCount - _state.AsteroidCount;
				for ( int i = 0; i < toSpawn; i++ ) {
					AsteroidGenerator.Instance.GenerateNewAsteroid(Random.insideUnitSphere * AsteroidSpawnRadius, 8f);
					_state.AsteroidCount++;
				}
			}
			if ( _state.RedBaseEntity == 0 ) {
				var b = CreateTeamBase(TeamType.Red, RedTeamPos, new Vector3(0,0,0) );
				_state.RedBaseEntity = b.ID;
			}

			if ( _state.BlueBaseEntity == 0 ) {
				var b = CreateTeamBase(TeamType.Blue, BlueTeamPos, new Vector3(0, 180, 0));
				_state.BlueBaseEntity = b.ID;
			}
		}

		public TeamBase GetBaseForTeam(TeamType team) {
			uint baseId = 0;
			if ( team == TeamType.Red ) {
				baseId = _state.RedBaseEntity;
			}
			if ( team == TeamType.Blue ) {
				baseId = _state.BlueBaseEntity;
			}
			var e = ServerEntityController.Instance.GetEntityById(baseId);
			if ( e == null ) {
				return null;
			}
			var cast = (TeamBase)e;
			return cast;
		}

		TeamBase CreateTeamBase(TeamType team, Vector3 position, Vector3 rotation) {
			var result = ServerEntityController.Instance.CreateNewEntity(EntityType.TeamBase, position, rotation, e => {
				var cast = (TeamBase)e;
				cast.Team = team;
			});

			for ( int i = 0; i < 8; i++ ) {
				ServerEntityController.Instance.CreateNewEntity(EntityType.SecurityTurret, position + Random.onUnitSphere * 30f, Random.rotation.eulerAngles, e => {
					var cast = (SecurityTurret)e;
					if ( cast != null ) {
						cast.Team = team;
					}
				});
			}

			return (TeamBase)result;
		}

		public override void Save() {
			base.Save();
			ServerSaveLoadController.Instance.SaveFileToDisk(StateFileName, _state);
		}
	}
}

